var e = getApp(),
    c = e.requirejs("api/index"),
    r = e.requirejs("core");
const myAudio = wx.createInnerAudioContext();
Page({
  data: {
    route: "member_index",
    menu: e.tabBar,
    menu_show: false,
    icons: e.requirejs("icons"),
    member: {},
    show: false,
    display: false,
    config: e.config,
    background: '#f2f2f2',
    default_pic: '/yb_mingpian/static/images/add_pic.jpg',
    is_writeoff: 2,
    options: {},
    duration: 500,
    interval: 5000,
    autoplay: true,
    circular: true,
    isPlay:false,
    nowtime:"00:00",
    currecttime: 0,
    totalTime: '',
    timechanging: false,
    audioIndex: -1,
    page_info: {},
    openImg: false,
    markers: [{
      iconPath: "/yb_mingpian/static/images/red_position_icon.png",
      title: '地理位置',
      latitude: 34.643330,
      longitude: 112.408450,
      width: 50,
      height: 50,
      callout: {
          content: '公司位置',
          company: '',
          color: '#000',
          fontSize: 14,
          borderRadius: 5,
          display: 'ALWAYS',
          textAlign: 'center',
          padding: 10,
          // borderWidth:1,
          // borderColor:"#ddd",
          bgColor:'#fff'
      }
    }],
  },
  //底部导航跳转
  menu_url: function(k) {
    r.menu_url(k, 2);
  },

  // 视频播放
  video: function (event) {
    var index = event.currentTarget.dataset['index'];

    if (!this.data.videoIndex) { // 没有播放时播放视频
      this.setData({
        videoIndex: index
      })
      var videoContext = wx.createVideoContext('video' + index)
      videoContext.play()
    } else {
      //停止正在播放的视频
      var videoContextPrev = wx.createVideoContext('video' + this.data.videoIndex)
      videoContextPrev.stop()
      //将点击视频进行播放
      this.setData({
        videoIndex: index
      })
      var videoContextCurrent = wx.createVideoContext('video' + index)
      videoContextCurrent.play()
    }
  },

  //跳转+收集表单id
  formSubmit: function (k) {
    var vv = { currentTarget: { dataset: {} } },
      data = k.detail.value;
    vv.currentTarget.dataset = data;
    r.menu_url(vv, 1);

    var d = {}
    d.formid = k.detail.formId;
    d.openid = getApp().getCache("userinfo").openid;
    d.username = getApp().getCache("userinfo").nickName;
    r.get('Market/getFormid', d, function (t) {
      console.log(t)
    })
  },

  //跳转
  to_url:function(k){
    r.menu_url(k, 1);
  },

  onGotUserInfo: function (q) {
    var that = this,
        cache = e.getCache("userinfo");

    // if (cache) {
    //     return;
    // }
    e.getUserInfo(q.detail.userInfo, function (t) {
      if (t != 1000) {
        var ucache = getApp().getCache("userinfo");
        if (ucache) {
          var options = that.data.options;
          that.getInfo();
          //getCurrentPages()[getCurrentPages().length - 1].onLoad();
          that.setData({
            display: false,
            //getPhoneAuth: getApp().globalData.getphone
          })
        }
      } else {
        that.setData({
          display: true
        })
      }

    }, q.detail.encryptedData, q.detail.iv);
  },

  // 取消登录
  cancel_auth: function () {
    this.setData({
      display: false
    })
  },

  onLoad: function(options) {
    var that = this;

    if (options != null && options != undefined) {
      this.setData({
        tabbar_index: options.tabbar_index ? options.tabbar_index : -1
      });
    }

    var cache = e.getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      getApp().authSwitch(function(res){
        if (res == 1) {
          that.setData({
            display: true
          })
        } else {
          that.setData({
            display: false
          })
        }
      })
    }

    // "" == e.getCache("userinfo") && (r.toast('您还没登录呢'),
    //     setTimeout(function() {
    //       wx.redirectTo({
    //         url: "/yb_mingpian/pages/index/index"
    //       })
    //     }, 2e3));

    // 分销信息
    r.get('Distribe/shareSetting', {}, function (t) {
      if (t.code == 0) {
        that.setData({
          shareSetting: t.info
        })
      }
    })

    //r.setting();
      that.getUserCenterData();
  },

  getUserCenterData: function() {
    var that = this;
    var user_id = e.getCache("userinfo").uid != undefined ? e.getCache("userinfo").uid : 0;
    c.indexMod(that, function (t) {
      console.log('ucenter',t);
      var cache = e.getCache("userinfo");
      if (t.is_writeoff == 1 && cache.nickName && cache.avatarUrl) {
        var scan_code = {
          'flag': "scan_code",
          'img': "/yb_mingpian/static/images/icon/scan.png",
          'name': "扫码核销",
          'path_url': "",
          'time_key': "",
          'type': "caidan",
        }

        for (var i = 0; i < t.index.length; i++) {
          if (t.index[i].type == 'caidan') {
            t.index.splice(i, 0, scan_code)
            break;
          }
        }

        that.setData({
          is_writeoff: 1
        });
      }

      console.log("new",t.index);
      that.setData({
          list: t.index,
          show: t.show,
          page_info: t.page
      });
      console.log("new",that.data.list);

        that.initpage();
        that.getInfo()
    },'userCenter', user_id);
  },
  upgrade:function(){
    wx.navigateTo({
      // url:"/yb_mingpian/pages/ruzhu/store"
      url: "/yb_mingpian/pages/member/upgrade/upgrade"
    })
  },

    // 设置页面数据
    initpage:function() {
      console.log("page_info",this.data.page_info);
        var that = this;
        wx.setNavigationBarColor({
            frontColor: that.data.page_info.text_color,
            backgroundColor: that.data.page_info.nv_color,
            animation: {
                duration: 0,
                timingFunc: "easeIn"
            }
        });

        wx.setNavigationBarTitle({
            title: that.data.page_info.name ? decodeURIComponent(that.data.page_info.name) : '会员中心'
        })

        wx.setBackgroundColor({
            backgroundColor: that.data.page_info.bg_color ? that.data.page_info.bg_color : '#f2f3f4'
        })

        // 开屏弹窗广告
        var showopenimg = e.getCache('open_img_show');
        var open_img_url = that.data.page_info.open_img.imgurl;
        if ((open_img_url != undefined && open_img_url != '') && (showopenimg == undefined || showopenimg == '')) {
            that.setData({
                openImg: true
            });
        } else {
          that.setData({
            openImg: false
          });
        }
    },

    // 关闭开屏弹窗广告
    openImg_close:function(){
        this.setData({
            openImg: false
        });
        // 半天弹1次
        e.setCache('open_img_show', true, 3600*12);
    },

  formBook: function (e) {
    var that = this,
      data = e.detail.value,
      uid = getApp().getCache("userinfo").uid;
    if (data.name == '') {
      r.error('姓名不能为空');
      return;
    } else if (uid == null || uid == undefined) {
      that.setData({
        display: true
      })
      return;
    } else if (data.phone.length != 11) {
      r.error('手机号格式不正确');
      return;
    }
    data.user_id = uid;
    r.get('Index/WriteBook', data, function (t) {
      if (t.code == 0) {
        that.setData({
          bookData: {}
        });
        r.success('提交成功');
      } else {
        r.alert(t.msg);
      }
    })

  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
      this.onLoad() || this.onShow()
      wx.stopPullDownRefresh();
  },

  // 获取统计信息
  getInfo: function() {
    var e = this;
    e.setData({
      background: getApp().config.background != undefined ? getApp().config.background : '#f2f2f2',
      font_color: getApp().config.font_color
    })
    console.log("config",getApp().config)
    r.get("user/Index", {
      uid: getApp().getCache("userinfo").uid != undefined ? getApp().getCache("userinfo").uid : 0
    }, function(r) {
      r.info.nickName = getApp().getCache("userinfo").nickName,
      r.info.avatarUrl = getApp().getCache("userinfo").avatarUrl
      console.log("memberinfo",r)
      e.setData({
        member: r.info
      })
    })
  },
  fail: function() {
    wx.redirectTo({
      url: "/yb_mingpian/pages/message/auth/index"
    })
  },
  onShow: function() {
    this.getInfo();
  },

  // 点击登录
  relogin: function() {
    var that = this;
    var cache = e.getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      that.setData({
        display: true
      })
    }
    /* wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.userInfo']) {
                e.getUserInfo();
                setTimeout(function() {
                  that.getInfo()
                }, 1e3)

              }
            }
          })
        }
      }
    }) */
  },

  /**
   * 地图
   */
  navigate: function (e) {
    var t = a.pdata(e);
    if (t.name && t.lat && t.lng) {
      a.tx_map(t.lat, t.lng, t.name)
    } else {
      a.toast('不能获取到该位置')
    }
  },
  phone: function (t) {
    r.phone(t)
  },
  // 万能表单提交
  formPower: function (e) {
    var cache = getApp().getCache("userinfo");
    if (!cache) {
      this.setData({
        display: true
      })
      return;
    }
    c.formSubmit(this, e);
  },

  bindPickerChange: function (e) {
    c.bindPickerChange(this, e);
  },
  listen_time_two: function (e) {
    c.listen_time_two(this, e);
  },
  chooseImageTap1: function (e) {
    var id = r.pdata(e).id;
    c.upload(this, id, 'form_pic', 1)
  },
  chooseImageTap2: function (e) {
    var id = r.pdata(e).id;
    c.upload(this, id, 'form_pic', 0)
  },
  Image_del: function (e) {
    c.Image_del(this, e);
  },

  /**
   * 图片预览
   */
  previewImage: function (e) {
    var url = r.pdata(e).url,
      arr = r.pdata(e).arr;
    r.previewImage(url, arr, 'imgurl')
  },

  /**
   * formid存缓存，做什么？
   */
  getFormId: function (event) {
    console.log("fom",event)
    if (!e.getCache('wx_form_id')) {
      e.setCache('wx_form_id',{'form_id': event.detail.formId},86400)
    }
    console.log("form_id",e.getCache('wx_form_id'))
  },

  /**
   * 跳转
   */
  goPath: function (ev) {
    var cache = e.getCache("userinfo");
    if (!cache) {
      this.setData({
        display: true
      })
      return;
    }

    var url = r.pdata(ev).url;
    console.log("url",url)
    if (url != undefined) {
      r.jump(url,1)
    }
  },

  /**
   * 扫码核销
   */
  scanCode: function () {
    wx.scanCode({
      //onlyFromCamera: true, // 只允许从相机扫码
      success(res) {
        console.log("scancode",res)
        if (res.errMsg != "scanCode:ok") {
          r.error("解析失败")
          return;
        }

        if (res.result == '') {
          r.error("内容错误")
          return;
        }

        r.jump('/yb_mingpian/pages/member/hexiao/index?order_no='+res.result, 1);
      },
      fail(res) {
        //r.error("扫码失败")
      },
    })
  },

  //音频组件播放
  play_status_change: function (e) {
    var audioSrc = r.pdata(e).src;
    var audioIndex = r.pdata(e).index;
    var that = this;
    myAudio.src = audioSrc;

    if (that.data.audioIndex == audioIndex){
      if (that.data.isPlay) {
        myAudio.pause();
        that.setData({isPlay: false})
      } else {
        myAudio.play();
        that.setData({isPlay: true});
      }
    } else {
      if (that.data.audioIndex >= 0) {
        myAudio.pause();
        that.setData({
          currecttime: 0,
          nowtime: "00:00",
          audioIndex: audioIndex
        });
        myAudio.play();
      } else {
        that.setData({
          audioIndex: audioIndex,
          isPlay: true
        })
        myAudio.play();
      }
    }

    myAudio.onPlay(function (res) {
      console.log("onPlay !!!!!!!!!");
      that.setData({
        isPlay: true
      })
    })

    myAudio.onError(function (res) {
      console.log("onError !!!!!!!!!",res);
    })

    myAudio.onEnded(function (res) {
      console.log("onEnded !!!!!!!!!");
      that.setData({
        currecttime: 0,
        isPlay: false,
        nowtime: "00:00"
      });
      //myAudio.destroy()
    })
    myAudio.onPause(function (res) {
      console.log("onPause !!!!!!!!!");
      that.setData({
        isPlay: false,
      })
    })
    myAudio.onTimeUpdate(function (res) {
      console.log("onTimeUpdate !!!!!!!!!");
      console.log("currentTime",parseInt(myAudio.currentTime));
      console.log("duration",parseInt(myAudio.duration));
      if (!that.data.timechanging) {
        that.setData({
          currecttime: parseInt(myAudio.currentTime),
          nowtime: that.timeformat(parseInt(myAudio.currentTime)),
          duration: parseInt(myAudio.duration),
          totalTime: that.timeformat(parseInt(myAudio.duration)),
        })
      }
    })
  },

  // 视频播放
  video: function (event) {
    var index = event.currentTarget.dataset['index'];

    if (!this.data.videoIndex) { // 没有播放时播放视频
      this.setData({
        videoIndex: index
      })
      var videoContext = wx.createVideoContext('video' + index)
      videoContext.play()
    } else {
      //停止正在播放的视频
      var videoContextPrev = wx.createVideoContext('video' + this.data.videoIndex)
      videoContextPrev.stop()
      //将点击视频进行播放
      this.setData({
        videoIndex: index
      })
      var videoContextCurrent = wx.createVideoContext('video' + index)
      videoContextCurrent.play()
    }
  },

  timeformat: function (time) {
    var m = parseInt(time / 60);
    m = m < 10 ? "0" + m : "" + m;
    var s = time % 60;
    s = s < 10 ? "0" + s : "" + s;
    return m + ":" + s;
  },
  timechanging: function (res) {
    console.log("timechanging !!!!!!!!");
    this.setData({
      timechanging: true,
    })
  },
  timechange: function (res) {
    console.log("timechange !!!!!!!!");
    var time = res.detail.value;
    myAudio.seek(time);

    this.setData({
      currecttime: time,
      nowtime: this.timeformat(time),
      timechanging: false,
    })
    myAudio.play();
  },
  onUnload:function(){
    myAudio.destroy()
  },
  onHide: function () {
    myAudio.destroy()
  }

})